<template>
  <el-dialog :visible.sync="dialogVisible" width="80%" :title="file.name">
    <el-scrollbar class="document-preview" style="height: 600px;">
      <div v-html="previewContent"></div>
    </el-scrollbar>
  </el-dialog>
</template>

<script>
import mammoth from 'mammoth';

export default {
  name: "DocumentPreview",
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    file: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      previewContent: '',
      dialogVisible: this.visible
    };
  },
  watch: {
    visible(newVal) {
      this.dialogVisible = newVal;
    },
    dialogVisible(newVal) {
      if (!newVal) {
        this.$emit('update:visible', false);
      }
    },
    file(newFile) {
      if (newFile) {
        if(!newFile.raw) return
        this.loadDocument(newFile.raw);
      }
    }
  },
  methods: {
    async loadDocument(file) {
      const reader = new FileReader();
      reader.onload = async (event) => {
        const arrayBuffer = event.target.result;
        const result = await mammoth.convertToHtml({ arrayBuffer });
        this.previewContent = result.value;
      };
      reader.readAsArrayBuffer(file);
    }
  }
};
</script>

<style scoped>
.document-preview {
  padding: 20px;
}
</style>
